package com.vc.videosdk.xlog

import com.elvishew.xlog.internal.Platform
import com.elvishew.xlog.printer.file.writer.Writer
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.io.FileWriter

/**

 * @Author : wy

 * @Time : On 2024/8/27 20:05

 * @Description : MyWriter

 */
class MyWriter : Writer(){

    /**
     * The name of opened log file.
     */
    private var logFileName: String? = null

    /**
     * The opened log file.
     */
    private var logFile: File? = null

    private var bufferedWriter: FileOutputStream? = null

    override fun open(file: File): Boolean {
        logFileName = file.name
        logFile = file
        var isNewFile = false

        // Create log file if not exists.
        if (!logFile!!.exists()) {
            isNewFile = try {
                val parent = logFile!!.parentFile
                if (!parent.exists()) {
                    parent.mkdirs()
                }
                logFile!!.createNewFile()
                true
            } catch (e: Exception) {
                e.printStackTrace()
                close()
                return false
            }
        }

        // Create buffered writer.
        try {
            bufferedWriter = FileOutputStream(logFile,true)
            if (isNewFile) {
                onNewFileCreated(logFile)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            close()
            return false
        }
        return true
    }

    override fun isOpened(): Boolean {
        return bufferedWriter != null && logFile!!.exists()
    }

    override fun getOpenedFile(): File? {
        return logFile
    }

    override fun getOpenedFileName(): String? {
        return logFileName
    }

    /**
     * Called after a log file is newly created.
     *
     *
     * You can do some initialization work to the new file, such as calling [.appendLog]
     * to add a file header.
     *
     *
     * Called in worker thread.
     *
     * @param file the newly created log file
     */
    fun onNewFileCreated(file: File?) {}

    override fun appendLog(log: String?) {
        try {
            bufferedWriter!!.write(log?.toByteArray())
            bufferedWriter!!.write("\n".toByteArray())

           // bufferedWriter!!.newLine()
            bufferedWriter!!.flush()
        } catch (e: Exception) {
            Platform.get().warn("append log failed: " + e.message)
        }
    }

    override fun close(): Boolean {
        if (bufferedWriter != null) {
            try {
                bufferedWriter!!.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        bufferedWriter = null
        logFileName = null
        logFile = null
        return true
    }
}